import { createStore, applyMiddleware, Middleware } from 'redux'
import { CreateJumpstateMiddleware } from 'jumpstate';

export let store: Record<string, any> = {};

/**
 * 动态切换reducer
 * @param {object} reducers
 */
export function injectAsyncReducer(reducers: Record<string, any> = {}) {
	Object.keys(reducers).forEach((key) => {
		if (!reducers[key]) {
			store.reducerManager.remove(key);
		} else {
			store.reducerManager.add(key, reducers[key]);
		}
	});
  store.replaceReducer(store.reducerManager.getReducer());
}

/**
 * 创建store对象
 * @param reducerManager reducer 管理器
 * @param middlewares 中间件
 */
export function createConfigStore(reducerManager, middlewares: Middleware[])  {
  const allMiddlewares  = [CreateJumpstateMiddleware(), ...middlewares]
  return function(initialState: Record<string, any> = {}) {
    store = applyMiddleware(...allMiddlewares)(createStore)(reducerManager.reducer, initialState);
    store.reducerManager = reducerManager;
    return store;
  }
}
